---
title: "Authentication"
description: "Secure your MCP connections with OAuth and bearer tokens"
icon: "shield"
tag: "New"
---

The mcp-use client supports multiple authentication methods for secure connections to MCP servers, including OAuth 2.0 with automatic token management, bearer token authentication, and custom authentication providers.

## Supported Authentication Methods

- **OAuth 2.0**: Complete OAuth flow with automatic Dynamic Client Registration (DCR)
- **Bearer Tokens**: API key and token-based authentication
- **Custom Headers**: Flexible authentication header support

<Tip>
**OAuth Made Simple**: The `useMcp` React hook automatically handles the entire OAuth flow, including token refresh and session management. No manual token handling required.
</Tip>

## OAuth Authentication

OAuth provides secure, token-based authentication with automatic token refresh and user consent flows.

<CodeGroup>
```typescript React Hook
import { useMcp } from 'mcp-use/react'

function MyComponent() {
  const mcp = useMcp({
    url: 'http://localhost:3000/mcp',
    callbackUrl: 'http://localhost:3000/callback',
  })

  // Handle authentication states
  if (mcp.state === 'pending_auth') {
    return (
      <button onClick={mcp.authenticate}>
        Authenticate with OAuth
      </button>
    )
  }

  if (mcp.state === 'authenticating') {
    return <div>Authenticating...</div>
  }

  if (mcp.state === 'ready') {
    return <div>Connected! {mcp.tools.length} tools available</div>
  }

  return <div>Connecting...</div>
}
```

```typescript HTTP Connector
import { createHTTPConnector } from 'mcp-use'

const connector = createHTTPConnector({
  url: 'http://localhost:3000/mcp',
  customHeaders: {
    Authorization: 'Bearer YOUR_ACCESS_TOKEN'
  }
})

// Use with MCP Client
const client = new Client({
  name: 'my-client',
  version: '1.0.0'
}, {
  capabilities: {}
})

await client.connect(connector)
```
</CodeGroup>

### Bearer Token Authentication

For servers requiring API keys or bearer tokens:

<CodeGroup>
```typescript React Hook
import { useMcp } from 'mcp-use/react'

function MyComponent() {
  const mcp = useMcp({
    url: 'http://localhost:3000/mcp',
    customHeaders: {
      Authorization: 'Bearer sk-your-api-key-here'
    }
  })

  // Use mcp.tools, mcp.callTool, etc.
}
```

```typescript HTTP Connector
import { createHTTPConnector } from 'mcp-use'

const connector = createHTTPConnector({
  url: 'http://localhost:3000/mcp',
  customHeaders: {
    Authorization: 'Bearer sk-your-api-key-here'
  }
})
```
</CodeGroup>

## Authentication Methods

### 1. OAuth 2.0 Authentication

OAuth 2.0 is the most common authentication method for MCP servers. mcp-use supports:

- **Dynamic Client Registration (DCR)** - Automatic client registration
- **Pre-registered Clients** - Using existing OAuth applications
- **Custom OAuth Providers** - With explicit metadata

#### Dynamic Client Registration

For servers that support DCR, you don't need to register a client manually:

#### Pre-registered OAuth Client

For servers requiring manual client registration:

#### OAuth Provider with Metadata

For servers with known OAuth endpoints, provide metadata upfront:

### 2. Bearer Token Authentication

For servers requiring simple API keys or bearer tokens:

### 3. Custom Authentication

For servers requiring custom authentication methods:

### 4. No Authentication

For public servers or servers without authentication:

## Complete Examples

### GitHub MCP Server Example

The GitHub MCP server requires OAuth authentication. You'll need to create a GitHub OAuth App first:

1. **Create a GitHub OAuth App**:
   - Go to [GitHub OAuth Apps](https://github.com/settings/applications/new)
   - Set **Application name**: `your-app-name`
   - Set **Homepage URL**: `http://localhost:8080` (or your custom port)
   - Set **Authorization callback URL**: `http://localhost:8080/callback` (or your custom port)
   - Click "Register application"
   - Copy your **Client ID** and **Client Secret**

2. **Configure mcp-use**:

### Multi-Server Configuration

You can mix different authentication methods across servers:

## OAuth Flow Modes

mcp-use supports two OAuth flow modes for client applications:

### Popup Flow (Default)

Opens OAuth authorization in a popup window. Best for desktop and web applications.

**Advantages:**
- User stays on the same page
- Better UX for web applications
- No navigation interruption

**Usage:**
```typescript
const mcp = useMcp({
  url: 'http://localhost:3000/mcp',
  callbackUrl: 'http://localhost:3000/callback',
  // Popup flow is the default
})
```

### Redirect Flow

Redirects the current window to the OAuth provider, then back to your app.

**Advantages:**
- Works in all browsers (popup blockers won't interfere)
- Better for mobile browsers
- More reliable across different environments

**Usage:**
```typescript
const mcp = useMcp({
  url: 'http://localhost:3000/mcp',
  callbackUrl: 'http://localhost:3000/callback',
  useRedirectFlow: true // Enable redirect flow
})
```

**Setup for Redirect Flow:**

1. Create a callback page in your app:
```typescript
// pages/callback.tsx or app/callback/page.tsx
import { onMcpAuthorization } from 'mcp-use/auth'
import { useEffect, useState } from 'react'

export default function OAuthCallback() {
  const [status, setStatus] = useState<'processing' | 'success' | 'error'>('processing')

  useEffect(() => {
    onMcpAuthorization()
      .then(() => {
        setStatus('success')
        // Redirect back to main app
        setTimeout(() => window.location.href = '/', 1000)
      })
      .catch((err) => {
        setStatus('error')
        console.error('Auth failed:', err)
      })
  }, [])

  if (status === 'processing') {
    return <div>Completing authentication...</div>
  }
  if (status === 'success') {
    return <div>Success! Redirecting...</div>
  }
  return <div>Authentication failed</div>
}
```

2. Configure your callback URL to match this route:
```typescript
const mcp = useMcp({
  url: 'http://localhost:3000/mcp',
  callbackUrl: 'http://localhost:3000/callback', // Your callback page
  useRedirectFlow: true
})
```

### Preventing Auto-Authentication

By default, mcp-use automatically triggers OAuth flow when a server requires authentication. You can disable this to show a manual authentication button:

```typescript
const mcp = useMcp({
  url: 'http://localhost:3000/mcp',
  preventAutoAuth: true // Show auth button instead of auto-triggering
})

// Manually trigger authentication
if (mcp.state === 'pending_auth') {
  return (
    <button onClick={mcp.authenticate}>
      Sign in to continue
    </button>
  )
}
```

## OAuth Flow Process

When OAuth authentication is required:

1. **Authorization Request**: Client requests authorization from the OAuth server
2. **User Consent**: User reviews and approves the requested permissions
3. **Redirect/Callback**: User is redirected back to your app with an authorization code
4. **Token Exchange**: Code is exchanged for an access token (handled automatically)
5. **Authenticated Connection**: Access token is used for all subsequent MCP requests

## Token Storage

Authentication data is stored securely:
- **Access Tokens**: `~/.mcp_use/tokens/{server_domain}.json`
- **Client Registrations**: `~/.mcp_use/tokens/registrations/{server_domain}_registration.json`

## Configuration Options

### OAuth Configuration Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `client_id` | string | No* | OAuth client ID (required if not using DCR) |
| `client_secret` | string | No | OAuth client secret (required if not using DCR) |
| `scope` | string | No | OAuth scopes to request |
| `callback_port` | integer | No | Port for OAuth callback (default: 8080) |
| `oauth_provider` | object | No | OAuth provider metadata |

*Required unless using Dynamic Client Registration

### Port Configuration

- **Default Port**: 8080
- **Custom Ports**: Any available port (e.g., 8081, 8082, 3000)
- **Port Conflicts**: mcp-use will check if the port is available before starting OAuth flow

## Troubleshooting

### Common Issues

#### OAuth Discovery Fails

If a server doesn't support OAuth discovery:
- Provide an `oauth_provider` with metadata
- Use a pre-registered `client_id`
- Check if the server requires different authentication

#### "Invalid redirect URI" Error

Solutions:
- Use Dynamic Client Registration (omit `client_id`)
- Register your app with supported redirect URIs
- Check if your provider supports wildcard redirect URIs
- Ensure callback URL matches your OAuth app configuration

#### Port Already in Use

If you get a port conflict error:
#### GitHub OAuth Issues

For GitHub specifically:
- Ensure your OAuth app callback URL matches: `http://localhost:8080/callback` (or your custom port)
- Use correct scopes: `repo`, `read:user`, etc.
- Check that your GitHub OAuth app is properly configured

### Debugging

Enable debug logging to see detailed authentication flow:

## Security Best Practices

- **Token Storage**: Tokens are stored with restricted permissions
- **Version Control**: Never commit authentication files to version control
- **CSRF Protection**: OAuth flow uses state parameter for CSRF protection
- **Localhost Callbacks**: All callbacks use localhost (127.0.0.1) for security
- **Isolation**: Each server's authentication is isolated
- **Environment Variables**: Use environment variables for sensitive data:

## Example Servers that support OAuth

### OAuth with DCR Support
- **Linear**: `https://mcp.linear.app/sse`
- **Asana**: `https://mcp.asana.com/sse`
- **Atlassian**: `https://mcp.atlassian.com/v1/sse`

### OAuth with Manual Registration
- **GitHub**: `https://api.githubcopilot.com/mcp/`

### Bearer Token
- Most API-based MCP servers

Check your server's documentation for specific authentication requirements and supported methods.
